package com.gengzp.rpc.proxy;

import com.gengzp.rpc.core.RpcCoreInvocationHandler;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.Proxy;

/**
 * @ClassName RpcServiceFactoryBean
 * @Description rpc服务代理工厂bean, 用于创建复杂的代理实现类对象
 * @Author gengzp
 * @Date 2025/10/27 16:18
 */
public class RpcServiceFactoryBean implements FactoryBean<Object> {

    /**
     * 远程调用的接口 .class 文件
     */
    private final Class<?> interfaceClass;

    /**
     * 指定的远程服务名
     */
    private final String serviceName;

    /**
     * bean 工厂
     */
    private final BeanFactory beanFactory;

    public RpcServiceFactoryBean(Class<?> interfaceClass, String serviceName, BeanFactory beanFactory) {
        this.interfaceClass = interfaceClass;
        this.serviceName = serviceName;
        this.beanFactory = beanFactory;
    }

    /**
     * 创建代理对象
     */
    @Override
    public Object getObject() {
        return Proxy.newProxyInstance(
                interfaceClass.getClassLoader(),
                new Class[]{interfaceClass},
                new RpcCoreInvocationHandler(serviceName, beanFactory)
        );
    }

    /**
     * 有了指定的返回类型后, 告诉Spring和IDE，这个FactoryBean生成的是interfaceClass类型的对象
     * 如果不指定对象, idea的依赖注入会爆红
     */
    @Override
    public Class<?> getObjectType() {
        return interfaceClass;
    }

}
